package me.xlgp.xiquzimu.data;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.core.Observable;
import me.xlgp.xiquzimu.dao.JuZhongDao;
import me.xlgp.xiquzimu.db.AppDatabase;
import me.xlgp.xiquzimu.designpatterns.ObserverHelper;
import me.xlgp.xiquzimu.model.JuZhong;

public class JuZhongRepository {
    public Observable<List<JuZhong>> list() {
        return AppDatabase.getInstance().juZhongDao().list().compose(ObserverHelper.transformer());
    }

    public void save(List<String> list) {
        List<JuZhong> juZhongList = new ArrayList<>();

        AppDatabase db = AppDatabase.getInstance();
        List<String> nameList = db.juZhongDao().listName();
        list.forEach(s -> {
            if (!nameList.contains(s)) {
                JuZhong juZhong = JuZhong.create();
                juZhong.setName(s);
                juZhongList.add(juZhong);
            }
        });
        if (!juZhongList.isEmpty()) {
            db.juZhongDao().insert(juZhongList);
        }
    }

    public Observable<Long> save(JuZhong juZhong) {
        long id = AppDatabase.getInstance().juZhongDao().insert(juZhong);
        return Observable.just(id).compose(ObserverHelper.transformer());
    }

    /**
     * 如果不存在 name则insert
     *
     * @param name
     * @return
     */
    public Observable<Long> save(String name) {
        JuZhongDao juZhongDao = AppDatabase.getInstance().juZhongDao();
        JuZhong juZhong = juZhongDao.getByName(name);
        if (juZhong == null) {
            juZhong = JuZhong.create();
            juZhong.setName(name);
        }
        return save(juZhong);
    }
}
